<script setup lang="ts">
import { ref, onUnmounted } from "vue";
import { aqiSO2Total } from "@/api";



const option = ref({});
const data1 = ref([])
const data2 = ref([])
const displayData1 = ref([])
const displayData2 = ref([])

// 初始化当前索引
const currentIndex = ref(14); // 开始时指向第一个要被移除的数据点后面的元素

const getData = () => {
  aqiSO2Total().then((res) => {
    if (res.code == 0) {
      const result1: any = []
      const result2: any = []
      Object.keys(res.data).forEach((k, index) => {
        result1.push(k)
        result2.push(res.data[k])
      })
      data1.value = result1
      data2.value = result2
      displayData1.value = result1.slice(0, 15)
      displayData2.value = result2.slice(0, 15)
      setOption();

    } else {
      // ElMessage.error(res.msg)
    }
  }).catch(err => {
    // ElMessage.error(err)
  });
};
getData();
const setOption = () => {
  option.value = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: displayData1.value,
      boundaryGap: false,
      axisLine: {
        lineStyle: {
          color: '#374a6a'
        }
      }
    },
    yAxis: {
      type: 'value',
      splitLine: { // 分割线配置
        show: true, // 显示分割线
        lineStyle: { // 分割线样式
          color: '#122641' // 分割线颜色
        }
      },
      axisLine: {
        lineStyle: {
          color: '#374a6a'
        }
      }
    },
    series: [{
      data: displayData2.value,
      type: 'bar'
    }]
  }
};

const chartRef = ref();

// // 每隔1秒更新数据
const timer = setInterval(function () {
  // 移除最老的数据点
  displayData1.value.shift();
  displayData2.value.shift();

  // 计算下一个数据点的索引
  currentIndex.value = (currentIndex.value + 1) % data1.value.length;

  // 添加新的数据点
  displayData1.value.push(data1.value[currentIndex.value]);
  displayData2.value.push(data2.value[currentIndex.value]);


  // 更新x轴和series数据
  // 更新图表数据
  chartRef.value.setOption({
    xAxis: {
      data: displayData1.value
    },
    series: [{
      data: displayData2.value
    }]
  });
}, 1000);

// 清理定时器
onUnmounted(() => clearInterval(timer));
</script>

<template>
  <v-chart class="chart" :option="option" ref="chartRef" />
</template>

<style scoped lang="scss"></style>
